<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="工区" prop="areaName">
        <el-select v-model="queryParams.areaName" placeholder="请选择工区" clearable @change="handleAreaChange">
          <el-option
            v-for="area in areaList"
            :key="area.areaName"
            :label="area.areaName"
            :value="area.areaName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="厂房" prop="factoryName">
        <el-select v-model="queryParams.factoryName" placeholder="请选择厂房" clearable @change="handleFactoryChange">
          <el-option
            v-for="factory in factoryList"
            :key="factory.factoryName"
            :label="factory.factoryName"
            :value="factory.factoryName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="段" prop="sectionName">
        <el-select v-model="queryParams.sectionName" placeholder="请选择段" clearable>
          <el-option
            v-for="section in sectionList"
            :key="section.sectionName"
            :label="section.sectionName"
            :value="section.sectionName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="槽号" prop="slotNumber">
        <el-input
          v-model="queryParams.slotNumber"
          placeholder="请输入槽号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报警类型" prop="alarmType">
        <el-select v-model="queryParams.alarmType" placeholder="请选择报警类型" clearable>
          <el-option label="电源箱门开" value="1" />
          <el-option label="槽控机门开" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="进行中" value="1" />
          <el-option label="已结束" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间区间">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:alarm:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:alarm:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-bell"
          size="mini"
          @click="showAlarmWindow = true"
        >实时报警</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="alarmLogList" @selection-change="handleSelectionChange" border fit>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="报警ID" align="center" prop="alarmId" width="80" />
      <el-table-column label="工区" align="center" prop="areaName" min-width="100" />
      <el-table-column label="厂房" align="center" prop="factoryName" min-width="100" />
      <el-table-column label="段" align="center" prop="sectionName" min-width="100" />
      <el-table-column label="槽号" align="center" prop="slotNumber" width="100" />
      <el-table-column label="报警描述" align="center" prop="alarmDescription" min-width="120" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.endTime">{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="持续时间" align="center" prop="duration" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.duration !== null && scope.row.duration !== undefined">
            {{ formatDuration(scope.row.duration) }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '1'" type="danger">进行中</el-tag>
          <el-tag v-else-if="scope.row.status === '0'" type="success">已结束</el-tag>
          <span v-else>{{ scope.row.status }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['business:alarm:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:alarm:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 实时报警通知悬浮窗口 -->
    <alarm-notification 
      v-if="showAlarmWindow"
      ref="alarmNotification" 
      :max-alarms="50"
      @close="showAlarmWindow = false"
    />

    <!-- 查看对话框 -->
    <el-dialog title="报警记录详情" :visible.sync="viewOpen" width="600px" append-to-body>
      <el-form ref="viewForm" :model="viewForm" label-width="120px">
        <el-form-item label="报警ID">
          <span>{{ viewForm.alarmId }}</span>
        </el-form-item>
        <el-form-item label="工区">
          <span>{{ viewForm.areaName || '-' }}</span>
        </el-form-item>
        <el-form-item label="厂房">
          <span>{{ viewForm.factoryName || '-' }}</span>
        </el-form-item>
        <el-form-item label="段">
          <span>{{ viewForm.sectionName || '-' }}</span>
        </el-form-item>
        <el-form-item label="槽号">
          <span>{{ viewForm.slotNumber }}</span>
        </el-form-item>
        <el-form-item label="报警类型">
          <el-tag v-if="viewForm.alarmType === '1'" type="danger">电源箱门开</el-tag>
          <el-tag v-else-if="viewForm.alarmType === '2'" type="warning">槽控机门开</el-tag>
        </el-form-item>
        <el-form-item label="报警描述">
          <span>{{ viewForm.alarmDescription }}</span>
        </el-form-item>
        <el-form-item label="开始时间">
          <span>{{ parseTime(viewForm.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </el-form-item>
        <el-form-item label="结束时间">
          <span v-if="viewForm.endTime">{{ parseTime(viewForm.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          <span v-else>-</span>
        </el-form-item>
        <el-form-item label="持续时间">
          <span v-if="viewForm.duration !== null && viewForm.duration !== undefined">
            {{ formatDuration(viewForm.duration) }}
          </span>
          <span v-else>-</span>
        </el-form-item>
        <el-form-item label="状态">
          <el-tag v-if="viewForm.status === '1'" type="danger">进行中</el-tag>
          <el-tag v-else-if="viewForm.status === '0'" type="success">已结束</el-tag>
        </el-form-item>
        <el-form-item label="创建时间">
          <span>{{ parseTime(viewForm.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </el-form-item>
        <el-form-item label="备注" v-if="viewForm.remark">
          <span>{{ viewForm.remark }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDoorAlarmLog, getDoorAlarmLog, delDoorAlarmLog, exportDoorAlarmLog } from "@/api/business/alarm";
import { listArea } from "@/api/workshop/area";
import AlarmNotification from "@/views/workshop/components/AlarmNotification";

export default {
  name: "DoorAlarmLog",
  components: {
    AlarmNotification
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报警日志表格数据
      alarmLogList: [],
      // 日期范围
      dateRange: [],
      // 查看对话框
      viewOpen: false,
      // 查看表单
      viewForm: {},
      // 实时报警抽屉显示状态
      showAlarmWindow: false,
      // 工区列表
      areaList: [],
      // 厂房列表
      factoryList: [],
      // 段列表
      sectionList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaName: null,
        factoryName: null,
        sectionName: null,
        slotNumber: null,
        alarmType: null,
        status: null,
        startTime: null,
        endTime: null
      }
    };
  },
  created() {
    this.getList();
    this.loadWorkshopData();
  },
  methods: {
    /** 加载工区数据 */
    loadWorkshopData() {
      listArea().then(response => {
        if (response.code === 200 && response.data) {
          this.areaList = response.data;
        }
      });
    },
    /** 工区变化时更新厂房列表 */
    handleAreaChange(areaName) {
      this.queryParams.factoryName = null;
      this.queryParams.sectionName = null;
      this.factoryList = [];
      this.sectionList = [];
      if (areaName) {
        const area = this.areaList.find(a => a.areaName === areaName);
        if (area && area.factories) {
          this.factoryList = area.factories;
        }
      }
    },
    /** 厂房变化时更新段列表 */
    handleFactoryChange(factoryName) {
      this.queryParams.sectionName = null;
      this.sectionList = [];
      if (factoryName) {
        const factory = this.factoryList.find(f => f.factoryName === factoryName);
        if (factory && factory.sections) {
          this.sectionList = factory.sections;
        }
      }
    },
    /** 查询报警日志列表 */
    getList() {
      this.loading = true;
      this.queryParams.startTime = this.dateRange && this.dateRange.length > 0 ? this.dateRange[0] : null;
      this.queryParams.endTime = this.dateRange && this.dateRange.length > 1 ? this.dateRange[1] : null;
      listDoorAlarmLog(this.queryParams).then(response => {
        this.alarmLogList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.alarmId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 查看按钮操作 */
    handleView(row) {
      const alarmId = row.alarmId || this.ids[0];
      getDoorAlarmLog(alarmId).then(response => {
        this.viewForm = response.data;
        this.viewOpen = true;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const alarmIds = row.alarmId || this.ids;
      this.$modal.confirm('是否确认删除报警日志编号为"' + alarmIds + '"的数据项？').then(function() {
        return delDoorAlarmLog(alarmIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/alarm/export', {
        ...this.queryParams
      }, `alarm_log_${new Date().getTime()}.xlsx`)
    },
    /** 格式化持续时间 */
    formatDuration(seconds) {
      if (seconds < 60) {
        return seconds + '秒';
      } else if (seconds < 3600) {
        const minutes = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return minutes + '分' + (secs > 0 ? secs + '秒' : '');
      } else {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;
        let result = hours + '小时';
        if (minutes > 0) {
          result += minutes + '分';
        }
        if (secs > 0) {
          result += secs + '秒';
        }
        return result;
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>

